<template>
	<v-content ref="content">
		<v-header title="课程详情" back background="#fff" transparent="none"></v-header>
		<div class="progress">
			<u-line-progress
				:percentage="((coursewaresIndex + 1) / coursewareLength) * 100"
				height="8"
				:showText="false"
				activeColor="#0195ff"
				inactiveColor="#f5f6f8"
			></u-line-progress>
		</div>
		<div class="title">
			{{ message.coursewareName }}

			<div class="last-time" v-if="message.studyStatus != 3 && message.studyTime">还需学习: {{ lastTime }}</div>
		</div>
		<div class="main padding">
			<template v-if="message.coursewareType == 1">
				<div v-if="message.needConver != 0">
					<div class="card" v-for="(item, index) in message.urls" :key="index">
						<div class="type">{{ formatExt(item) }}</div>
						<div class="name">{{ formatName(item) }}</div>
					</div>
				</div>
				<div v-else>
					<div class="card" v-for="(item, index) in message.urls" :key="index">
						<image
							class="image"
							mode="widthFix"
							:src="item"
							@click="previewImage(message.urls, index)"
						></image>
					</div>
				</div>
			</template>
			<template v-else-if="message.coursewareType == 2">
				<u-parse :content="message.coursewareContent"></u-parse>
			</template>
			<template v-else-if="message.coursewareType == 3">
				<video class="video" :src="item" v-for="(item, index) in message.urls" :key="index"></video>
			</template>

			<div style="height: 400rpx"></div>
		</div>
		<div class="footer padding">
			<div class="button round radius relative" v-if="coursewaresIndex" @click="toPrev"></div>
			<div class="button radius" v-if="coursewaresIndex == coursewareLength - 1" @click="toNext">完成学习</div>
			<div class="button radius" v-else @click="toNext">下一节</div>
		</div>
	</v-content>
</template>

<script>
import { mapGetters } from "vuex"
import mixins from "@/mixins"

let timer = null

export default {
	name: "learn-content",
	mixins: [mixins],
	data() {
		return {
			startTime: new Date().getTime(),
			isSave: false,
			lastTime: "",
		}
	},
	computed: {
		message() {
			return this.$store.state.study.coursewares
		},
		...mapGetters(["coursewaresIndex", "coursewareLength"]),
		studyTime() {
			return this.message.studyTime * 60
		},
	},
	onUnload() {
		if (!this.isSave) {
			this.toEnd()
		}
		this.lastTime = "已完成"
	},
	methods: {
		async init() {
			this.isSave = false
			await this.$store.dispatch("getCourseware", this.query)
			this.startCountdown()
		},

		startCountdown() {
			if (this.message.studyStatus == 3) {
				return
			}
			const time = this.studyTime - this.getStudyTime()
			this.lastTime = time > 0 ? this.getFormatStudyTime(time) : "已完成"

			if (this.lastTime != "已完成") {
				timer = setTimeout(() => {
					this.startCountdown()
				}, 1000)
			}
		},

		toPrev() {
			if (this.coursewaresIndex == 0) {
				this.showMessage.modal({
					title: "提示",
					content: "是否返回课程详情？",
					confirm: async (next, cancel) => {
						try {
							await this.toEnd()
							next()
						} catch (error) {
							cancel()
						}
					},
				})
			} else {
				async function toPrev() {
					uni.showLoading({ title: "加载中..." })
					try {
						await this.toEnd()
						this.startTime = new Date().getTime()
						this.query.coursewareId = this.$store.getters.prevCoursewaresId
						this.query.chapterId = this.$store.getters.prevChapterId
						this.init()
					} catch (error) {
						throw error
					} finally {
						uni.hideLoading()
					}
				}

				const studyTime = this.message.studyTime * 60

				if (studyTime > this.getStudyTime() && this.message.studyStatus != 3) {
					this.showMessage.modal({
						title: "提示",
						content: `学习时间不足，是否暂停学习？<br /> 已学习时长：${this.getFormatStudyTime(
							this.getStudyTime()
						)} <br /> 本节学习时长：${this.message.studyTime}分钟`,
						confirm: async (next, cancel) => {
							try {
								await toPrev.call(this)
								next()
							} catch (error) {
								cancel()
							}
						},
					})
					return
				} else {
					toPrev.call(this)
				}
			}
		},
		async toNext() {
			function toNext() {
				return new Promise(async (reslove, reject) => {
					if (this.coursewaresIndex == this.coursewareLength - 1) {
						this.showMessage.modal({
							title: "提示",
							content: "是否完成本次学习？",
							confirm: async (next, cancel) => {
								try {
									await this.toEnd()
									uni.showToast({
										title: "学习完成",
										icon: "success",
									})
									setTimeout(() => {
										this.toPage(-1)
									}, 1500)
									next()
									reslove()
								} catch (error) {
									cancel()
									reject()
								}
							},
						})
					} else {
						uni.showLoading({ title: "加载中..." })
						try {
							await this.toEnd()
							this.startTime = new Date().getTime()
							this.query.coursewareId = this.$store.getters.nextCoursewaresId
							this.query.chapterId = this.$store.getters.nextChapterId
							this.init()
							reslove()
						} catch (error) {
							reject()
						} finally {
							uni.hideLoading()
						}
					}
				})
			}

			const studyTime = this.message.studyTime * 60
			if (studyTime > this.getStudyTime() && this.message.studyStatus != 3) {
				this.showMessage.modal({
					title: "提示",
					content: `学习时间不足，是否暂停学习？<br /> 已学习时长：${this.getFormatStudyTime(
						this.getStudyTime()
					)} <br /> 本节学习时长：${this.message.studyTime}分钟`,
					confirm: async (next, cancel) => {
						try {
							await toNext.call(this)
							next()
						} catch (error) {
							cancel()
						}
					},
				})
				return
			} else {
				await toNext.call(this)
			}
		},

		async toEnd() {
			if (this.message.studyStatus == 3) {
				return true
			}
			this.isSave = true
			return await this.$axios.post("/api/study/course/studyCourseLog/edit", {
				courseId: this.query.courseId,
				chapterId: this.query.chapterId,
				coursewareId: this.query.coursewareId,
				studyTime: this.getStudyTime(), // 秒
				id: this.message.logId,
			})
		},

		formatName(url) {
			return url.split("/").pop()
		},
		formatExt(url) {
			return url.split(".").pop()
		},
		getStudyTime() {
			return (+this.message.alreadyStudyTime + (new Date().getTime() - this.startTime) / 1000) | 0
		},
		getFormatStudyTime(time) {
			const hour = (time / 3600) | 0
			const minute = ((time % 3600) / 60) | 0
			const second = time % 60
			return `${hour ? hour + "小时" : ""}${minute ? minute + "分钟" : ""}${second ? second + "秒" : ""}`
		},
	},
}
</script>

<style lang="scss" scoped>
.title {
	text-align: center;
	font-size: 36rpx;
	font-weight: 700;
	padding-top: 15rpx;
	.last-time {
		padding-bottom: 10rpx;
		padding-top: 5rpx;
		font-weight: 500;
		font-size: 26rpx;
		color: #666;
	}
}
.main {
	padding-top: 50rpx;
	height: 100%;
	overflow: auto;
	box-sizing: border-box;
}

.video {
	width: 100%;
	display: block;
	margin-bottom: 10rpx;
	height: 400rpx;
}

.footer {
	height: 140rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	z-index: 9;
	box-sizing: border-box;
	background: #fff;
	.button {
		width: 100%;
		height: 80rpx;
		font-size: 34rpx;
		background: $color;
		&.round {
			width: 80rpx;
			flex: none;
			&::before {
				content: "";
				position: absolute;
				top: 0;
				bottom: 0;
				right: 0;
				left: 7rpx;
				border-bottom: 6rpx solid currentColor;
				border-left: 6rpx solid currentColor;
				border-right: 6rpx solid transparent;
				border-top: 6rpx solid transparent;
				border-radius: 5rpx;
				transform: rotate(45deg);
				width: 20rpx;
				height: 20rpx;
				margin: auto;
			}
		}
	}
}
.image {
	width: 100%;
}
</style>
